<?php

namespace app\common\model\mall\shop;

use think\Db;

class Shop extends \think\Model
{
    // 表名
    protected $name = 'mall_shop_shop';
    
    protected $pk = 'id';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    
    // 追加属性
    protected $append = [
        'state_text',
        'status_text',
        'area_ids_text',
        'bank_area_ids_text',
    ];

    protected static function init()
    {
        $config = get_addon_config('mall');
        self::afterInsert(function ($row) use ($config) {
            //新增积分汇总记录
            \app\common\model\mall\shop\Raty::create(["shop_id"=>$row->id]);
        });
        self::afterDelete(function ($row) use ($config) {
            //删除积分汇总记录
            \app\common\model\mall\shop\Raty::destroy($row->id);
        });
    }

    public function getShopimgAttr($value, $data)
    {
        if(config("mall.mallcdn") && !stristr($value, config("mall.mallcdn"))) {
            $value = config("mall.mallcdn").$value ;
        }else $value = cdnurl($value);
        return $value;
    }

    public function getAreaIdsTextAttr($value, $data)
    {
        $exist = \think\Db::query("show tables like'".config('database.prefix')."area'");
        if(!$exist) return "";
        $value = $value ? $value : explode(",", $data['areaIds']);
        $name = Db::name("area")->where("id","in",$value)->column("name");
        return implode('', $name);
    }

    public function getBankAreaIdsTextAttr($value, $data)
    {
        $exist = \think\Db::query("show tables like'".config('database.prefix')."area'");
        if(!$exist) return "";
        $value = $value ? $value : explode(",", $data['bankAreaIds']);
        $name = Db::name("area")->where("id","in",$value)->column("name");
        return implode('', $name);
    }

    public function getStateList()
    {
        return ['0' => __('State 0'),'1' => __('State 1')];
    }

    public function getStatusList()
    {
        return [
            'normal' => __('Normal'),
            'hidden' => __('Hidden'),
            'fillin'  =>  __('Fillin'),
            'audit'  =>  __('Audit'),
            'reject'  =>  __('Reject'),
            'pause'  =>  __('Pause'),
        ];
    }

    public function getStateTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['shopAtive']) ? $data['shopAtive'] : '');
        $list = $this->getStateList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    /**
     * 店铺金额变动记录
     * @param int    $money   余额
     * @param int    $shop_id 店铺ID
     * @param string $memo    备注
     */
    public static function money($money, $shop_id, $memo)
    {
        $shop = self::get($shop_id);
        if ($shop && $money != 0) {
            $before = $shop->money;
            $after = $shop->money + $money;
            $shop->save(['money' => $after]);
            //如果是负数，还要计算支出总额
            if($money<0){
                $shop->save(['paymentMoney'=>($shop->paymentMoney - $money)]);
            }
            //写入日志
            MoneyLog::create(['shop_id' => $shop_id, 'money' => $money, 'before' => $before, 'after' => $after, 'memo' => $memo]);
        }
    }

    /**
     * 获取商家认证
     */
    public static function shopAccreds($shop_id){
        $accreds = Db::name("mall_shop_accred_access")->alias('sa')
            ->join('__MALL_SHOP_ACCRED__ a','a.id=sa.accred_id','left')
            ->field('a.name,a.img')
            ->where(['sa.shop_id'=> $shop_id])
            ->select();
        return $accreds;
    }
    
    /**
     * 获取店铺首页信息
     */
    public function getShopInfo($shop_id = 1){
        $rs = $this->where(['id'=>$shop_id,'state'=>1,'status'=>'normal'])
            ->field('shopNotice,id,shopImg,name,shopAddress,shopQQ,shopWangWang,shopTel,serviceStartTime,longitude,latitude,serviceEndTime,shopKeeper,mapLevel,goodscat_ids')
            ->with("raty")->find();
        //认证
        $accreds = $this->shopAccreds($rs['id']);
        $rs['accreds'] = $accreds;
        //分类
        $goodsCatMap = [];
        $goodsCats = Db::name('mall_goods_cat')->alias('cs')
            ->where('id', 'in', $rs['goodscat_ids'])
            ->where('status',"normal")
            ->field($rs["id"].' shop_id,name')->select();
        foreach ($goodsCats as $v){
            $goodsCatMap[] = $v['name'];
        }
        $rs['catshops'] = (isset($goodsCatMap))?implode(',',$goodsCatMap):'';
        
        $shopAds = array();
        $shopset = Db::name('mall_shop_set')->where("shop_id=".$rs['id'])->find();
        // 访问普通店铺首页 或 自营店铺首页才取出轮播广告
        if(isset($isAds['shop_id']) || $shop_id){
            //广告
            if($shopset["ads"]!=''){
                $shopAdsImg = explode(',',$shopset["ads"]);
                $shopAdsUrl = explode(',',$shopset["adsurl"]);
                for($i=0;$i<count($shopAdsImg);$i++){
                    $adurl = isset($shopAdsUrl[$i])?$shopAdsUrl[$i]:"";
                    $adsImg = $shopAdsImg[$i];
                    $shopAds[$i]["adImg"] = $adsImg;
                    $shopAds[$i]["adUrl"] = $adurl;
                    $shopAds[$i]['isOpen'] = false;
                    if(stripos($adurl,'http:')!== false || stripos($adurl,'https:')!== false){
                        $shopAds[$i]['isOpen'] = true;
                    }
                }
            }
        }
        $rs['ads'] = $shopAds;
        $rs['title'] = $shopset["title"];
        $rs['desc'] = $shopset["desc"];
        $rs['keywords'] = $shopset["keywords"];
        $rs['banner'] = $shopset["banner"];
        $rs['mobilebanner'] = $shopset["mobilebanner"];
        //关注
        $f = new \app\common\model\mall\user\Favorite;
        $rs['favShop'] = $f->checkFavorite($shop_id,1);
        //热搜关键词
        $sc = new \app\common\model\mall\shop\Set();
        $rs['shopHotWords'] = $sc->where("shop_id",$shop_id)->column("hotwords");
        return $rs;
    }

    public function raty(){
        return $this->hasOne('\\app\\common\\model\\mall\\shop\\Raty', 'shop_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function extra(){
        return $this->hasOne('\\app\\common\\model\\mall\\shop\\Extra', 'shop_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    /**
     * 首页店铺街列表
     */
    public function indexShopQuery($num=4){
        $cacheData = cache('PC_SHOP_STREET');
        if(!$cacheData){
            $cacheData = $this->alias('s')
                ->join('__MALL_SHOP_SET__ sc','s.id=sc.shop_id','inner')
                ->join('__MALL_GOODS_RECOMMEND__ r','s.id=r.dataId')
                ->where(['r.goodsCatId'=>0,'s.state'=>1,'s.status'=>'normal','r.dataSrc'=>1,'r.dataType'=>0])
                ->field('s.id,s.name,s.shopAddress,s.shopimg,sc.streetimg')
                ->order('r.weigh asc')->select();
            if(count($cacheData)==0){
                $cacheData = $this->alias('s')
                    ->join('__MALL_SHOP_SET__ sc','s.id=sc.shop_id','inner')
                    ->where(['s.state'=>1,'s.status'=>'normal'])
                    ->field('s.id,s.name,s.shopAddress,s.shopimg,sc.streetimg')
                    ->limit($num)->select();
            }
            cache('PC_SHOP_STREET',$cacheData,86400);
        }
        return $cacheData;
    }

    /**
     * 判断是否申请入驻过
     */
    public function checkApply(){
        $user_id = (int)cookie('uid');
        $rs = $this->where(['user_id'=>$user_id])->find();
        if(!empty($rs)){
            $MALL_USER = session('MALL_USER');
            $MALL_USER['tempShopId'] = $rs->id;
            session('MALL_USER',$MALL_USER);
            session('apply_step',$rs['applyStep']);
        }
        return $rs;
    }

    /**
     * 获取商家入驻资料
     */
    public function getShopApply(){
        $user_id = (int)cookie('uid');
        $rs = $this->alias('s')
            ->join('__MALL_SHOP_EXTRA__ e','s.id=e.shop_id','inner')
            ->where('s.user_id',$user_id)->find();
        if(!empty($rs)){
            $rs = $rs->toArray();
            $goodscats = explode(",", $rs["goodscat_ids"]);
            $rs['catshops'] = [];
            foreach ($goodscats as $v){
                $rs['catshops'][$v] = true;
            }
        }
        return $rs;
    }

    /**
     *  获取店铺的默认运费
     */
    public function getShopsFreight($shop_id){
        return $this->where(["status"=>"normal","id"=>$shop_id])->field('freight')->find();
    }

    /**
     * 获取IP所在地区经纬度
     */
    function IpLocation(){
        $key = config('mall.mapKey');
        $ip = request()->ip();
        $url = "http://apis.map.qq.com/ws/location/v1/ip?ip=".$ip."&key=".$key;
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        $res = json_decode($res,true);
        $data['latitude'] = 0;
        $data['longitude'] = 0;
        if($res['status']==0){
            $data['latitude'] = $res['result']['location']['lat'];
            $data['longitude'] = $res['result']['location']['lng'];
        }
        return $data;
    }



}
